package com.bai.edu.service.impl;

import com.bai.base.exceptionHandler.BaiException;
import com.bai.edu.entity.Chapter;
import com.bai.edu.entity.Video;
import com.bai.edu.entity.chapter.ChapterVo;
import com.bai.edu.entity.chapter.VideoVo;
import com.bai.edu.mapper.ChapterMapper;
import com.bai.edu.service.ChapterService;
import com.bai.edu.service.VideoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author bai
 * @since 2023-07-25
 */
@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter> implements ChapterService {

    @Autowired
    private VideoService videoService;


    //课程大纲列表
    @Override
    public List<ChapterVo> getChapterVideoByCourseId(String courseId) {
          //查询章节
        QueryWrapper<Chapter> chapterWrapper = new QueryWrapper<>();
        chapterWrapper.eq("course_id",courseId);
        List<Chapter> chapters = baseMapper.selectList(chapterWrapper);
        //查询小节
        QueryWrapper<Video> videoWrapper = new QueryWrapper<>();
        videoWrapper.eq("course_id",courseId);
        List<Video> videos = videoService.list(videoWrapper);
        //数据封装
        List<ChapterVo> list = new ArrayList<>();
        for (Chapter chapter : chapters) {
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(chapter,chapterVo);
            List<VideoVo> videoVos = new ArrayList<>();
            for (Video video : videos) {
                if (video.getChapterId().equals(chapterVo.getId())){
                    VideoVo videoVo = new VideoVo();
                    BeanUtils.copyProperties(video,videoVo);
                    videoVos.add(videoVo);
                }
            }
            chapterVo.setChildren(videoVos);
            list.add(chapterVo);
        }
        return list;
    }

    //删除章节
    @Override
    public boolean removeChapter(String chapterId) {
        QueryWrapper<Video> videoQueryWrapper = new QueryWrapper<>();
        videoQueryWrapper.eq("chapter_id",chapterId);
        int count = videoService.count(videoQueryWrapper);
        if (count>0){
            throw new BaiException(2001,"有小节");
        }else {
            int i = baseMapper.deleteById(chapterId);
            return i>0;
        }
    }

    @Override
    public void removeChaptByCourseId(String courseId) {
        QueryWrapper<Chapter> chapterQueryWrapper = new QueryWrapper<>();
        chapterQueryWrapper.eq("course_id",courseId);
        baseMapper.delete(chapterQueryWrapper);
    }
}
